package com.xiaoshuidi.cloud.module.iot.controller.admin.lyimport;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StringUtils;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDo;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceRepository;
import com.xiaoshuidi.cloud.module.iot.enums.BrandEnum;
import com.xiaoshuidi.cloud.module.iot.enums.DeviceTypeEnum;
import com.xiaoshuidi.cloud.module.iot.service.impl.LocalDeviceServiceImpl;
import com.xiaoshuidi.cloud.module.iot.uitils.UUidUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class LeiYouDeviceImportListener extends AnalysisEventListener<LeiYouDeviceImportVo> {

    private final static Logger LOGGER = LoggerFactory.getLogger(LocalDeviceServiceImpl.class);

    private List<LeiYouDeviceImportVo> dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private String apiNo;

    private DeviceRepository deviceDataAccess;

    private static final int BATCH_COUNT = 100;

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Override
    public void invoke(LeiYouDeviceImportVo readingOrderImportVO, AnalysisContext analysisContext) {
        // 将读取到的数据添加到集合中
        dataList.add(readingOrderImportVO);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (dataList.size() >= BATCH_COUNT) {
            this.saveData(dataList);
            // 存储完成清理 list
            dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!dataList.isEmpty()) {
            this.saveData(dataList);
        }
    }

    public LeiYouDeviceImportListener(DeviceRepository deviceDataAccess, String apiNo) {
        this.deviceDataAccess = deviceDataAccess;
        this.apiNo = apiNo;
    }

    public void saveData(List<LeiYouDeviceImportVo> dataList) {
        //查询这个账号下水滴IOT有的设备
        List<TbDeviceDo> localDeviceList = deviceDataAccess.getDeviceListByOneApiNo(apiNo);
        //水滴有，第三方没有设备集合(iot内该删除的设备)
//        List<TbDeviceDo> deletedDeviceList = localDeviceList.stream().filter(tbDeviceDo -> !dataList.stream().map
//                (LeiYouDeviceImportVo::getDeviceThirdNo).collect(Collectors.toList()).contains(tbDeviceDo.getDeviceThirdNo())).collect(Collectors.toList());
        //第三方有，水滴没有设备集合(iot内该添加的设备)
        List<LeiYouDeviceImportVo> addVoList = dataList.stream().filter(tbDeviceDo -> !localDeviceList.stream().map
                (TbDeviceDo::getDeviceThirdNo).collect(Collectors.toList()).contains(tbDeviceDo.getDeviceThirdNo())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(addVoList)) {
            List<TbDeviceDo> addEntityList = new ArrayList<>();
            for (LeiYouDeviceImportVo leiYouDeviceImportVo : addVoList) {
                if (leiYouDeviceImportVo.getDeviceName() == null) {
                    continue;
                }
                if (!(leiYouDeviceImportVo.getDeviceName().endsWith("水") || leiYouDeviceImportVo.getDeviceName().endsWith("电"))) {
                    continue;
                }

                TbDeviceDo tbDeviceDo = new TbDeviceDo();
                BeanUtil.copyProperties(leiYouDeviceImportVo, tbDeviceDo);
                tbDeviceDo.setBrandNo(BrandEnum.LEIYOU.getBrand());
                tbDeviceDo.setBrandName(BrandEnum.LEIYOU.getBrandName());
                tbDeviceDo.setPowerStatus(tbDeviceDo.getOnlineStatus());
                tbDeviceDo.setApiNo(apiNo);
                tbDeviceDo.setDeviceNo(UUidUtils.generateUuid());
                tbDeviceDo.setDeviceType(leiYouDeviceImportVo.getDeviceName().endsWith("水") ? DeviceTypeEnum.COLD_WATERMETE_TYPE_ENUM.getCode() : DeviceTypeEnum.AMMETER.getCode());
                tbDeviceDo.setDeviceModel("LY_".concat(tbDeviceDo.getDeviceType()));
                if (StringUtils.isNotBlank(leiYouDeviceImportVo.getReportTimeStr())) {
                    tbDeviceDo.setReportTime(LocalDateTime.parse(leiYouDeviceImportVo.getReportTimeStr(), formatter));
                } else {
                    tbDeviceDo.setReportTime(LocalDateTime.now());
                }
                tbDeviceDo.setTenantId(SecurityFrameworkUtils.getLoginUser().getTenantId());
                addEntityList.add(tbDeviceDo);
            }

            if (CollectionUtils.isNotEmpty(addEntityList)) {
                //添加设备到数据库
                boolean addResult = deviceDataAccess.saveBatch(addEntityList);
            }
        }
    }
}
